<?php

namespace app\controller\api;

use app\service\ShellRunnerService;
use app\validate\MqValidate;
use share\controller\ApiBaseController;
use think\Log;

class MqController extends ApiBaseController{

    public function initValidate(){
        $this->validate = new MqValidate();
    }

    /**
     * 
     */
    public function callback_action(){
        if(!$this->check_callback_access()){
            return self::fail('no access to call this api',401);
        }
        $input = $this->check();
        $command = sprintf("%s%scli.php CMqBack call_by_cache_key %s",dirname(dirname(__DIR__)),DIRECTORY_SEPARATOR,$input['token']);
        $fullCommand = ShellRunnerService::getCommandOfRunBackground($command);
        $fp = popen($fullCommand,'r');
        // pclose($fp);
        return self::ok([
            'input' => $input,
            'fp' => $fp === false ? 0 : 1,
        ]);       
    }

    public function callback_direct_action(){
        if(!$this->check_callback_access()){
            return self::fail('no access to call this api',401);
        }
        $input = $this->check();
        $service = $input['service'];
        $params = $input['params'];
        $serviceInfo = explode('@',$service);
        $class = $serviceInfo[0];
        $method = $serviceInfo[1];
        if(!method_exists($class,$method)){
            trace("mq.callback service ".$service." not exist!",Log::ERROR);
            return self::ok();
        }
        $res = null;
        if(isset($params[0])){ //数组形式的参数
            $res = call_user_func_array([$class,$method],$params);
        }
        else{
            $res = call_user_func([$class,$method],$params);
        }
        return self::ok($res);
    }

    /**
     * 检查回调权限
     */
    protected function check_callback_access(){
        $ip = $this->request->ip();
        $ipPrefix = substr($ip,0,3);
        //如果是本地局域网的 
        if($ipPrefix === '127' || $ipPrefix === '192' || $ipPrefix === '172' || $ipPrefix === '10.'){
            return true;
        }
        $param = $this->request->param();
        $mqKey = config("MQ_AUTH_KEY");
        $mqSecret = config("MQ_AUTH_SECRET");
        if(isset($param[$mqKey]) && $param[$mqKey] === $mqSecret){
            return true;
        }
        return false;
    }
}